package proj.reseau;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

public class BufferMap {
	private BitSet bufferMap;
	private int length;
	private List<FilePart> filePart;
	private byte[] bytes;
	public BufferMap(int nbPieces) {
		//System.out.println("Taille de la nouvelle buffermap : " + nbPieces);
		length = nbPieces;
		bufferMap = new BitSet(nbPieces);
		filePart = new ArrayList<FilePart>();
	}

	public void setBufferMap(String s)
	{
		/*byte[] bytes=s.getBytes();
		this.bytes=bytes;
		int p = 0;
		for (byte b : bytes) {
			int val = b;
			for (int i = 0; i < 8; i++) {
				if((val & 128) == 1)
					bufferMap.set(p+i, true);
				else
					bufferMap.set(p+i, false);
			}
			p += 8;
		}*/
		System.out.println("avant : "+s);
		for (int i = 0; i < s.length(); i++) {
			if(s.charAt(i)=='0')
			{
				bufferMap.set(i, false);
			}
			else
			{
				bufferMap.set(i, true);
			}
		}
		System.out.println("apres: ");
		this.printBufferMap();
	}
	
	public int getNeededIndex(int startIndex)
	{
		for (int i = startIndex; i < length; i++) {
			if(!bufferMap.get(i))
				return i;
		}
		return -1;
	}
	
	boolean havePiece(int index)
	{
		return bufferMap.get(index);
	}

	void addPiece(int position)
	{
		bufferMap.set(position);
	}

	void printBufferMap()
	{
		for (int i = 0; i < length; i++) {
			if(bufferMap.get(i))
				System.out.print("1");
			else
				System.out.print("0");
		}
	}
	
	public void setSeedBuffMap()
	{
		bufferMap.set(0, length, true);
	}
	
	String toBinaryString()
	{
		char[] s = new char [length];
		//System.out.println(length);
		for (int i = 0; i < length; i++) {
			if(bufferMap.get(i))
			{
				s[i]='1';
			}
			else
			{
				s[i]='0';
			}
		}
		String st=new String(s);
		//System.out.println(st);
		return st;
	}
}
